using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Text.RegularExpressions;
using MediaPortal.GUI.Library;
using MediaPortal.Util;
using MediaPortal.Dialogs;
using System.Xml;
using System.Xml.XPath;
using System.IO;

namespace MediaPortal.GUI.iPlayer
{
    public class iPlay_top : GUIWindow
    {
        #region SkinControlAttributes
        [SkinControlAttribute(10)]
        protected GUIFacadeControl facadeview = null;
        [SkinControlAttribute(2)]
        protected GUIButtonControl btnFavorite = null;
        [SkinControlAttribute(3)]
        protected GUIButtonControl btnList = null;
        [SkinControlAttribute(4)]
        protected GUISelectButtonControl btnDay = null;
        [SkinControlAttribute(5)]
        protected GUISelectButtonControl btn_chan = null;
        [SkinControlAttribute(6)]
        protected GUISelectButtonControl btnOmroep = null;
        [SkinControlAttribute(7)]
        protected GUISelectButtonControl btn_genre = null;
        [SkinControlAttribute(8)]
        protected GUIButtonControl btnMoetJeZien = null;
        [SkinControlAttribute(123)]
        protected GUIImage image = null;

        #endregion

        #region Variables

        public static Boolean debugMode = false;
        Preferences prefs = new Preferences();
        private common_classes commonStuff = new common_classes();   //some common classes
        private List<Serie> series = new List<Serie>();       //start a series list
        private TVProgramList programs = new TVProgramList();   //full list of programs
        private List<Serie> favorites = new List<Serie>();       //favorites list

        //we will need something here for later
        private List<NavigationItem> navItems = new List<NavigationItem>();    //navigation menu
        private bool ViewFavorites = false;
        private bool ViewMustSee = false;
        public static string[] linkNavs = new string[] { "nav_letter", "nav_dag", "nav_net" };

        private String MainUrlBody = String.Empty;
        #endregion

        // With GetID it will be an window-plugin / otherwise a process-plugin
        // Enter the id number here again

        public override int GetID
        {
            get
            {
                return 5680;
            }
            set
            {

            }
        }

        public override bool Init()
        {
             // process to update the lists;
            //programs.LoadFromFile();
            //programs.loadNamesFromFile();
            return Load(GUIGraphicsContext.Skin + @"\iPlay_BBC_top.xml");
        }

        public override void OnAction(MediaPortal.GUI.Library.Action action)
        {
            if (action.wID == MediaPortal.GUI.Library.Action.ActionType.ACTION_SELECT_ITEM && !facadeview.Focus
                && !btnFavorite.Focus && !btnList.Focus)
            {
                focusFacade();
                return;
            }
            else if (action.wID == MediaPortal.GUI.Library.Action.ActionType.ACTION_PLAY && facadeview.Focus)
            {
                string mmsurl = string.Empty;
                if (ViewFavorites)
                    mmsurl = string.Empty; //mmsurl = GetPlayUrl(favorites[facadeview.SelectedListItemIndex].lastEmissionUrl);
                else
                    mmsurl = string.Empty; //mmsurl = GetPlayUrl(series[facadeview.SelectedListItemIndex].lastEmissionUrl);

                focusFacade();
                // PlayEmission(mmsurl);
            }
     //       else if (action.wID == Action.ActionType.ACTION_PREVIOUS_MENU)
     //           ViewFavorites = true;  //worker.cancelWorker();

            base.OnAction(action);
        }

        protected override void OnClicked(int controlId, GUIControl control, MediaPortal.GUI.Library.Action.ActionType actionType)
        {
            
            // Clicking on an unused selectbutton results in -1 being sent
            if (control.SelectedItem < 0) return;

            if (control == btnList)
            {
                ViewFavorites = false;
                image.FileName = "nothing.png";
                GUIPropertyManager.SetProperty("#list", "FULL LIST");
                ShowList(series);
            }
             if (control == btnFavorite)
             {
                 ViewFavorites = true;
                 image.FileName = "nothing.png";
                 GUIPropertyManager.SetProperty("#list", "MY FAVORITES");
                 ShowList(favorites);
             }

            //  if (control == btnDag)   //day
            //  {
            //      ViewMustSee = false;
            //      GetLinkNav("nav_dag");
            //      GetEmissions(navItems[btnDag.SelectedItem].url);
            //  }
              if (control == btn_chan)   //channel
              {
                  ViewFavorites = false;
                  GUIPropertyManager.SetProperty("#list", "CHANNEL");
                  GetProgramsChan(programs.thePrograms, btn_chan.SelectedLabel);
              }
            //  if (control == btnOmroep)   //
            //  {
            //      ViewMustSee = false;
            //      GetSelectNav("omroep");
            //      GetEmissions(navItems[btnOmroep.SelectedItem].url);
            //  }
              if (control == btn_genre)    //genre
              {
                  ViewFavorites = false;
                  GUIPropertyManager.SetProperty("#list", "GENRE");
                  GetProgramsGenre(programs.thePrograms, btn_genre.SelectedLabel);
              }
            //  if (control == btnMoetJeZien)
            //  {
            //      ShowMustSee();
            //  }
            if (control == facadeview)
            {
                if (ViewFavorites)
                {
                    //SecondScreen.ViewVideo = true;
                    //NLGemistEmissionInfo.Url = favorites[facadeview.SelectedListItemIndex].url;
                    iplay_series.Url = facadeview.SelectedListItem.Label;
                    GUIWindowManager.ActivateWindow(5679);  //series stuff
                }
                //else if (ViewMustSee)
                //{
                //   // string mmsurl = GetPlayUrl(programs.theProgramNames[facadeview.SelectedListItemIndex].pn);                    
                //   // PlayEmission(mmsurl);
                //}
                else
                {
                    iplay_series.Url = facadeview.SelectedListItem.Label;
                    GUIWindowManager.ActivateWindow(5679);      //get episodes view
                }
            }
            base.OnClicked(controlId, control, actionType);

            if (control != facadeview)
            {
                GUIControl.FocusControl(GUIWindowManager.ActiveWindow, control.GetID);
                facadeview.Focus = true;
            }
        }

        public override bool OnMessage(GUIMessage message)
        {
            if (message.Message == GUIMessage.MessageType.GUI_MSG_ITEM_FOCUS || message.Message == GUIMessage.MessageType.GUI_MSG_ITEM_FOCUS_CHANGED)
                if (facadeview.SelectedListItemIndex != -1 && ViewMustSee == true)
                {
                   // GUIPropertyManager.SetProperty("#votes", series[facadeview.SelectedListItemIndex].watched);
                   // GUIPropertyManager.SetProperty("#rating", "" + series[facadeview.SelectedListItemIndex].rating);
                   // GUIPropertyManager.SetProperty("#plot", series[facadeview.SelectedListItemIndex].plot);
                    //imgList.Dimmed = true;
                    //lblBekeken.Dimmed = true;
                }
            return base.OnMessage(message);
        }

        /// <summary>
        /// Actions when page is loaded
        /// </summary>
        protected override void OnPageLoad()
        {
           // updateList();
            programs.LoadFromFile();
            programs.loadNamesFromFile();
            
            ShowGroup(false);   //allows to actual program data related to showmustsee
            //GetNav(programs.theProgramNames, btnTitle);
            //GetNav("nav_dag", btnDag);
            GetChanNav(programs.thePrograms, btn_chan);
            GetGenreNav(programs.thePrograms, btn_genre);
            favorites = Favorites.LoadFavoritesXML("Fav");
            GetProgramsList(programs.thePrograms, programs.theProgramNames);

            if (ViewFavorites)
            {
                ViewFavorites = true;
                image.FileName = "nothing.png";
                GUIPropertyManager.SetProperty("#list", "My FAVORITES");
                ShowFavorites(favorites);
            }
            else
            {

                ShowList(series);
                image.FileName = "nothing.png";
                GUIPropertyManager.SetProperty("#list", "FULL LIST");
                ViewFavorites = false;
            }
            base.OnPageLoad();
        }

        /// <summary>
        /// Actions when page is closed
        /// </summary>
        protected override void OnPageDestroy(int new_windowId)
        {
            //MainUrlBody = string.Empty;

            Favorites.SaveFavoritesXML("Fav", favorites);
            
            favorites.Clear();
            base.OnPageDestroy(new_windowId);
        }


        /// <summary>
        /// Show the favorites list
        /// </summary>
        /// <param name="favor">serie list </param>
        private void ShowFavorites(List<Serie> favor)
        {
            ViewFavorites = true;
             
             facadeview.View = GUIFacadeControl.ViewMode.List;
             facadeview.Clear();

             foreach (Emission ep in favor)
             {

                 GUIListItem item = new GUIListItem();
                 item.Label = ep.title;
                 item.IsFolder = true;
                 Util.Utils.SetDefaultIcons(item); //Utils.SetDefaultIcons(item);
                 facadeview.Add(item);
             }
        }

        /// <summary>
        /// Show a list of programs
        /// </summary>
        /// <param name="favor"> </param>
        private void ShowList(List<Serie> progs)
        {
            //ShowGroup(true);
            facadeview.View =  GUIFacadeControl.ViewMode.List;
            facadeview.Clear();

            foreach (Serie ep in progs)
            {

                GUIListItem item = new GUIListItem();
                item.Label = ep.title;
                item.IsFolder = true;
                Util.Utils.SetDefaultIcons(item); //Utils.SetDefaultIcons(item);
                facadeview.Add(item);
            }

          //  GUIControl.FocusControl(GUIWindowManager.ActiveWindow, facadeview.GetID);
          //  facadeview.Focus = true;
        }



        protected override void OnShowContextMenu()
        { 
            GUIListItem item = facadeview.SelectedListItem;

            GUIDialogMenu menu = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
            menu.Reset();
            menu.SetHeading("Extra Options:");
            if (ViewFavorites == false)
                menu.Add("Add to favorites");
            if (ViewFavorites == true)
                menu.Add("Remove from favorites");
            menu.DoModal(GetID);
            if (menu.SelectedId == -1) return;
            if (menu.SelectedLabelText == "Add to favorites")
                favorites.Add(series[facadeview.SelectedListItemIndex]);///need to add proper info here
            if (menu.SelectedLabelText == "Remove from favorites")
            {
                favorites.RemoveAt(facadeview.SelectedListItemIndex);
                ShowFavorites(favorites);
            }
            base.OnShowContextMenu();
        }

        private void GetProgramsChan(List<TVProgram> progs, string channelSelected)
        {
            ViewMustSee = false;
            ShowGroup(false);
            bool searchMatch = false;

            facadeview.View = GUIFacadeControl.ViewMode.List;
            facadeview.Clear();
            
            //get image from logos directory
            string thumbsFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\Team MediaPortal\\MediaPortal\\Thumbs\\tv\\logos\\";
                        //if (File.Exists(thumbsFolder + "BBC ONE.png"))
                        //{
                        //    image.FileName = thumbsFolder + channelSelected.Replace("_", " ") + ".png";
                        //}
                        //          else
                       {
                            for (int i=1; i< progs.Count; i++)
                            {
                                if (progs[i].Channel == channelSelected)
                                {
                                    image.FileName = commonStuff.DownloadImage(progs[i].ChannelLogoURL);
                                    i = progs.Count;
                                }
                            }

                            
                        }
           
            foreach (TVProgram ep in progs)
            {
                if (ep.Channel == channelSelected)
                {
                    searchMatch = false;

                    if (facadeview.SubItemCount < 1)
                    {
                        GUIListItem item = new GUIListItem();
                        item.Label = ep.ProgramName;
                        item.IsFolder = true;
                        Util.Utils.SetDefaultIcons(item); //Utils.SetDefaultIcons(item);
                        facadeview.Add(item);

                    }
                    else
                    {
                        for (int i = 0; i < facadeview.SubItemCount; i++)
                        {
                            if (ep.ProgramName == facadeview.GetSubItem(i).ToString())
                            {
                                
                                searchMatch = true;
                            }
                        }
                        if (searchMatch == false)
                        {
                            GUIListItem item = new GUIListItem();
                            item.Label = ep.ProgramName;
                            item.IsFolder = true;
                            Util.Utils.SetDefaultIcons(item); //Utils.SetDefaultIcons(item);
                            facadeview.Add(item);
                        }
                    }

                }
            }

            
            //  GUIControl.FocusControl(GUIWindowManager.ActiveWindow, facadeview.GetID);
            //  facadeview.Focus = true;
        }

        private void GetProgramsGenre(List<TVProgram> progs, string genreSelected)
        {
            ViewMustSee = false;
            ShowGroup(false);
            bool searchMatch = false;

            facadeview.View = GUIFacadeControl.ViewMode.List;
            facadeview.Clear();

            foreach (TVProgram ep in progs)
            {
                if (ep.ProgramGenre == genreSelected)
                {
                    searchMatch = false;

                    if (facadeview.SubItemCount < 1)
                    {
                        GUIListItem item = new GUIListItem();
                        item.Label = ep.ProgramName;
                        item.IsFolder = true;
                        Util.Utils.SetDefaultIcons(item); //Utils.SetDefaultIcons(item);
                        facadeview.Add(item);
                    }
                    else
                    {
                        for (int i = 0; i < facadeview.SubItemCount; i++)
                        {
                            if (ep.ProgramGenre == facadeview.GetSubItem(i).ToString())
                                searchMatch = true;
                        }
                        if (searchMatch == false)
                        {
                            GUIListItem item = new GUIListItem();
                            item.Label = ep.ProgramName;
                            item.IsFolder = true;
                            Util.Utils.SetDefaultIcons(item); //Utils.SetDefaultIcons(item);
                            facadeview.Add(item);
                        }
                    }
                }
            }

            //  GUIControl.FocusControl(GUIWindowManager.ActiveWindow, facadeview.GetID);
            //  facadeview.Focus = true;
        }

        private void GetProgramsList(List<TVProgram> progs, List<TVProgramLite> program_names)
        {
            bool searchMatch = false;
            int progIndex = 0;  // index value
                                    
            foreach (TVProgramLite ep in program_names)
            {
                searchMatch = false;  //re-initialise search match every new element in program_names
                progIndex = 0; //re-init seriesIndex so search starts from top of program-names

                while (searchMatch == false)
                {
                    if (ep.pn == progs[progIndex].ProgramName)
                    {
                        
                    string title = progs[progIndex].ProgramName;
                    title = StringUtils.ConvertString(title);

                    string seriesurl = progs[progIndex].ProgramLink;
                    seriesurl = StringUtils.ConvertString(seriesurl);

                    string image = progs[progIndex].ProgramImage;
                    image = StringUtils.ConvertString(image);

                    string chan = progs[progIndex].ChannelLogoURL;
                    chan = StringUtils.ConvertString(chan);

                    series.Add(new Serie(title, seriesurl, image, chan));                     
                    searchMatch = true;  // drop out of loop

                    }
                    else
                    {
                        progIndex++;
                    }
                }
            }
        }
        
        /// <summary>
        /// Get the options for the letterbuttons in the main screen
        /// </summary>
        private void GetSelectNav(string search)
        {
            navItems.Clear();

            if (MainUrlBody == String.Empty)
                navItems.Clear();     //MainUrlBody = worker.GetUrl(host);

                navItems.Clear();//navItems.Add(new NavigationItem(m1.Groups["name"].Value, host + "/index.php/selectie?searchitem=" + search + "&" + search + "=" + m1.Groups["url"].Value));

            navItems.RemoveAt(0);
        }

        private void GetLinkNav(string search)
        {
            navItems.Clear();

            if (MainUrlBody == String.Empty)
                MainUrlBody = String.Empty; // worker.GetUrl(host)
        }

        /// <summary>
        /// Get the options for the channels in the main screen
        /// </summary>
        /// <param name="search">letterbutton name fe. title or genre</param>
        /// <param name="btn">ButtonControlName that needs to be filled</param>
        private void GetChanNav(List<TVProgram> progs, GUISelectButtonControl btn)
        {
            //if (Array.IndexOf(linkNavs, search) >= 0) GetLinkNav(search);
            //else GetSelectNav(search);
            bool searchMatch = false;

            btn.Clear();
            btn.Selected = false;

            foreach (TVProgram item in progs)
            {
                searchMatch = false;

                if (btn.SubItemCount < 1)
                    btn.AddSubItem(item.Channel);
                else
                {
                    for (int i = 0; i < btn.SubItemCount; i++)
                    {
                        if (item.Channel == btn.GetSubItem(i).ToString())
                            searchMatch = true;
                    }
                    if (searchMatch==false)
                    {
                        btn.AddSubItem(item.Channel);
                    }
                }
            }
        }


        /// <summary>
        /// Get the options for the genres in the main screen
        /// </summary>
        /// <param name="progs"> the TVProgram database</param>
        /// <param name="btn">ButtonControlName that needs to be filled</param>
        private void GetGenreNav(List<TVProgram> progs, GUISelectButtonControl btn)
        {
            bool searchMatch = false;

            btn.Clear();
            btn.Selected = false;

            foreach (TVProgram item in progs)
            {
                searchMatch = false;

                if (btn.SubItemCount < 1)
                    btn.AddSubItem(item.ProgramGenre);
                else
                {
                    for (int i = 0; i < btn.SubItemCount; i++)
                    {
                        if (item.ProgramGenre == btn.GetSubItem(i).ToString())
                            searchMatch = true;
                    }
                    if (searchMatch == false)
                    {
                        btn.AddSubItem(item.ProgramGenre);
                    }
                }
            }
        }

        private void ShowGroup(bool show)
        {
            //imgList.Visible = show;
            //textBox.Visible = show;
            //lblBekeken.Visible = show;
        }

        private void focusFacade()
        {
            if (facadeview.Count > 0 && !facadeview.Focus)
            {
                GUIControl.FocusControl(GUIWindowManager.ActiveWindow, facadeview.GetID);
                facadeview.Focus = true;
            }
            else if (facadeview.Count == 0)
            {
                GUIControl.FocusControl(GUIWindowManager.ActiveWindow, btnFavorite.GetID);
                facadeview.Focus = false;   // should be false
            }
        }

        private class NavigationItem
        {
            public string name, url;

            public NavigationItem(string name, string url)
            {
                this.name = name;
                this.url = url;
            }

            public override string ToString()
            {
                return "name: " + name + ", url: " + url;
            }
        }

      

    }

}